#项目初始化[主程文件]
import os
from flask import Flask
from flask_script import Manager
from flask_sqlalchemy import SQLAlchemy
from flask_redis import FlaskRedis
from flask_session import Session
from flask_migrate import Migrate,MigrateCommand
from flask_jsonrpc import JSONRPC
from faker import Faker
from flask_jwt_extended import JWTManager
from flask_admin import Admin,AdminIndexView
from flask_babelex import Babel

from application.utils.config import load_config
from application.utils.session import init_session
from application.utils.logger import Log
from application.utils.commands import load_command
from application.utils import init_blueprint
from application.utils.language.message_text import Message as message
from application.utils.language.status_number import Status as status
from application.utils.alioss import OSS

# 创建数据库链接对象
db = SQLAlchemy()

# 日志对象
log = Log()

# 初始化jsonrpc模块
jsonrpc = JSONRPC(service_url='/api')

# redis链接对象
redis = FlaskRedis()

# Session存储对象
session_store = Session()

# 数据迁移实例对象
migrate = Migrate()

# jwt认证模块实例化
jwt = JWTManager()

# flask-admin模块初始化
admin = Admin()

#翻译模块，国际化本地化模块
babel = Babel()

#阿里云对象存储
oss=OSS()

def init_app(config_path):
    """全局初始化"""
    # 创建app应用对象
    app = Flask(__name__)

    # 项目根目录
    app.BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

    # import sys
    # sys.path.append(os.path.join(app.BASE_DIR, "application/utils/language"))

    # 加载配置
    Config = load_config(config_path)
    app.config.from_object(Config)

    # 数据库初始化
    db.init_app(app)
    redis.init_app(app)

    # session存储初始化
    init_session(app)
    session_store.init_app(app)

    # 初始化终端脚本工具
    manager = Manager()

    manager.app = app

    # 数据迁移初始化
    migrate.init_app(app,db)
    # 添加数据迁移的命令到终端脚本工具中
    manager.add_command('db', MigrateCommand)

    # 日志初始化
    app.log = log.init_app(app)

    # 注册自定义命令
    load_command(manager)

    # 初始化json-rpc
    app.jsonrpc = jsonrpc
    jsonrpc.init_app(app)

    # jwt初始化
    jwt.init_app(app)

    #注册蓝图
    init_blueprint(app)

    # admin站点
    admin.init_app(app)
    admin.name = app.config['FLASK_ADMIN_NAME']
    admin.template_mode = app.config['TEMPLATE_MODE']

    # 翻译模块[国际化，本地化]
    babel.init_app(app)

    # 数据种子生成器[faker]
    app.faker = Faker(locale=app.config.get("LANGUAGE"))

    #阿里云对象安装注册
    oss.init_app(app)

    return manager